//
//  store.m
//  pipi
//
//  Created by zhao ys on 5/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "store.h"
#import <StoreKit/StoreKit.h>


static store * _sharedStore = nil;

@implementation store

@synthesize products = _products;

+(store*) sharedStore {
	if (_sharedStore == nil) {
		_sharedStore = [[store alloc] init];
	}
	return _sharedStore;
}


- (void) requestProductData
{
	if (_canMakePayments) {
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		NSArray * product_list = [defaults arrayForKey:@"StoreProducts"];
		
		SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithArray:product_list]];
		request.delegate = self;
		[request start];
	}
}

-(id) init {
	if ((self = [super init])) {
		_products = nil;
		if ([SKPaymentQueue canMakePayments]) {
			_canMakePayments = YES;
		} else {
			_canMakePayments = NO;
		}
		if (_canMakePayments) {
			[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
			[self requestProductData];
		}
	}
	return self;
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
	_products = [NSMutableArray array];
	for (SKProduct * product in response.products) {
		[_products setObject:product forKey:product.productIdentifier];
	}
	[request autorelease];
}


-(BOOL) makePayment:(NSString *)id {
	if (_canMakePayments) {		
		
		[[SKPaymentQueue defaultQueue] addPayment:[SKPayment paymentWithProductIdentifier:id]];
		return YES;
	}
	return NO;
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased: 
			{	
                //[self completeTransaction:transaction];
				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
				//NSArray * product_list = [defaults arrayForKey:@"ChargeProducts"];
				//[product_list 			
                break;
			}
            case SKPaymentTransactionStateFailed:
                //[self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                //[self restoreTransaction:transaction];
            default:
                break;
        }
		[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    }
}

@end
